﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using AMS.Core.Data;
using AMS.DD35.DbAccess;

namespace AMS.DD35.DbAccess.SqlClient
{
    public class SqlRegisterConnector : IRegisterConnector
    {
        IConfiguration _config;

        public SqlRegisterConnector(IConfiguration configuration)
        {
            _config = configuration;
        }

        public bool UsernameExists(string username)
        {
            using (SqlConnection conn = new SqlConnection(_config.ConnectionString))
            {
                string commandString = String.Format("SELECT COUNT(*) FROM {0}.{1}.Users WHERE username=@username", _config.Database, _config.Schema);
                using (SqlCommand command = new SqlCommand(commandString, conn))
                {
                    command.Parameters.AddWithValue("@username", username);
                    try
                    {
                        conn.Open();
                        using (SqlDataReader dataReader = command.ExecuteReader())
                        {
                            while (dataReader.Read())
                            {
                                return Convert.ToInt32(dataReader[0]) > 0;
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception("username check failed", ex);
                    }
                }
            }

            throw new Exception("username check failed");
        }

        public void InsertUserInfo(string username, string passwordHash, string email)
        {
            using (SqlConnection conn = new SqlConnection(_config.ConnectionString))
            {
                string commandString = String.Format("INSERT INTO {0}.{1}.Users (username, password_hash, email_address) VALUES (@username, @pHash, @email)",
                    _config.Database, _config.Schema);
                using (SqlCommand command = new SqlCommand(commandString, conn))
                {
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@pHash", passwordHash);
                    command.Parameters.AddWithValue("@email", email);
                    try
                    {
                        conn.Open();
                        command.ExecuteNonQuery();
                    }
                    catch (SqlException ex)
                    {
                        throw new Exception("register failed", ex);
                    }
                }
            }
        }
    }
}
